package Dao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

public class register extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection con;
        String sql;
        ResultSet resultSet;
        PreparedStatement preparedStatement;
        try {
            boolean could_register=false;
            Class.forName("com.mysql.jdbc.Driver");
            con= DriverManager.getConnection("jdbc:mysql://localhost:3306/it?useUnicode=true&characterEncoding=utf8","root","123456");
            req.setCharacterEncoding("utf8");
            String name=req.getParameter("name"),password=req.getParameter("password");
            System.out.println(name+password);
            sql="select * from login where name= ?";
            preparedStatement=con.prepareStatement(sql);
            preparedStatement.setString(1,name);
            resultSet=preparedStatement.executeQuery();
            if(!resultSet.next())
                could_register=true;
            if(could_register){
                System.out.println("注册成功");
                sql="insert into login (name,password,zong_price,buy_name) values(?,?,0,'')";
                preparedStatement=con.prepareStatement(sql);
                preparedStatement.setString(1,name);
                preparedStatement.setString(2,password);
                preparedStatement.executeUpdate();
                resp.sendRedirect("login.html");
            }
            else{
                System.out.println("不可注册");
                resp.sendRedirect("register.html");
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}
